package com.hwh.bootdemoweb.Netty第六章.双向通信;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author wenhao hu
 * @title: BitClient
 * @projectName bootdemoweb
 * @description: TODO
 * @date 2021/12/2316:54
 */
@Slf4j
public class BitClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = msg instanceof ByteBuf ? ((ByteBuf) msg) : null;
                                assert buf != null;
                                System.out.println("client:" + buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                }).connect(new InetSocketAddress(8080)).sync().channel();
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                if ("q".equals(line)){
                    //由于close也是阻塞方法，所以关闭操作也不适合放在线程里
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"Input").start();
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("进入关闭之后的操作");
                //优雅的停止group，停止接受任务，并在处理完剩余任务后停止运行
                group.shutdownGracefully();
            }
        });
    }
}
